<?php


namespace services\base;

use Yii;
use common\components\Service;
use common\models\base\BcBodyParts;
use common\helpers\ArrayHelper;


class BcBodyPartsService extends Service
{


    /**
     * 半舱311部位列表
     *
     * @return array
     */
    public function getList($params = null)
    {
        $status = $params['status'] ?? 0;
        $statusArray = [BcBodyParts::STATUS_INVALID, BcBodyParts::STATUS_ENABLE];
        if ($status == BcBodyParts::STATUS_ENABLE) {
            $statusArray = [BcBodyParts::STATUS_ENABLE];
        }
        $list = BcBodyParts::find()->select('id, bc_parts_name, status')
            ->where(['status' => $statusArray])
            ->orderBy(['status' => SORT_DESC, 'sort' => SORT_ASC])
            ->asArray()
            ->all();

        return [
            'list' => $list,
        ];
    }

    /**
     * 新增半舱311部位
     *
     * @param $params
     * @return array
     */
    public function create($params)
    {
        $exists = $this->checkName([
            'bc_parts_name' => $params['bc_parts_name'],
            'status' => [BcBodyParts::STATUS_ENABLE, BcBodyParts::STATUS_INVALID]
        ]);
        if ($exists) {
            return ['code' => 422, 'message' => '该半舱311部位名称已存在'];
        }

        $model = new BcBodyParts();
        $model->bc_parts_name = $params['bc_parts_name'];
        $model->status = $params['status'];
        if ($model->save() == false) {
            return ['code' => 422, 'message' => '新增失败'];
        }
        return ['code' => 200, 'message' => '新增成功'];
    }

    /**
     * 判断是否存在
     *
     * @param $where
     * @return bool
     */
    public function checkName($where)
    {
        return BcBodyParts::find()->where($where)->exists();
    }

    /**
     * 编辑状态
     *
     * @param int $id
     * @param int $status
     * @return array
     */
    public function updateStatus(int $id, int $status)
    {
        $exists = $this->checkName(['id' =>$id]);
        if (!$exists) {
            return ['code' => 422, 'message' => '该半舱311部位不存在'];
        }
        $data = BcBodyParts::updateAll(['status' => $status], ['id' => $id]);
        if (!$data) {
            return ['code' => 422, 'message' => '修改失败'];
        }
        return ['code' => 200, 'message' => '修改成功'];
    }

    /**
     * 编辑半舱311部位
     *
     * @param array $params
     * @return array
     */
    public function update(array $params)
    {
        $exists = $this->checkName(['id' => $params['id']]);
        if (!$exists) {
            return ['code' => 422, 'message' => '数据不存在'];
        }

        $model = BcBodyParts::findOne($params['id']);
        $effectTypeIs =  BcBodyParts::findOne(
            [
                'bc_parts_name' => $params['bc_parts_name'],
                'status' => [BcBodyParts::STATUS_ENABLE, BcBodyParts::STATUS_INVALID],
            ]
        );
        if ($effectTypeIs && $effectTypeIs->id != $params['id']) {
            return ['code' => 422, 'message' => '该半舱311部位名称已存在'];
        }

        $model->bc_parts_name = $params['bc_parts_name'];
        $model->status = $params['status'];
        if ($model->save() == false) {
            return ['code' => 422, 'message' => '修改失败'];
        }
        return ['code' => 200, 'message' => '修改成功'];
    }

    /**
     * 删除半舱311部位
     *
     * @param int $id
     * @return array
     */
    public function delete(int $id)
    {
        $exists = $this->checkName(['id' => $id]);
        if (!$exists) {
            return ['code' => 422, 'message' => '该半舱311部位不存在'];
        }
        $data =  BcBodyParts::updateAll(['status' => BcBodyParts::STATUS_DELETE], ['id' => $id]);
        if (!$data) {
            return ['code' => 422, 'message' => '删除失败'];
        }
        return ['code' => 200, 'message' => '删除成功'];
    }

    /**
     * 真删除白白管家部位
     *
     * @param int $id
     * @return array|mixed
     */
    public function trueDelete(int $id)
    {
        $bodyPartsArray = BcBodyParts::find()
            ->select('id, bc_parts_name, pid')
            ->where(['id' => $id])
            ->asArray()
            ->all();

        if (!$bodyPartsArray) {
            return ['code' => 422, 'message' => '该部位不存在'];
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {

            $member = Yii::$app->user->identity->member;

            // 如果是一级部位
            if ($bodyPartsArray[0]['pid'] == 0) {

                // 需要筛选全部子集批量删除
                $childBodyParts = BcBodyParts::find()
                    ->select('id, bc_parts_name, pid')
                    ->andWhere(['>', 'pid', 0])
                    ->asArray()
                    ->all();

                $childBodyArray = ArrayHelper::getChilds($childBodyParts,$id);

                foreach ($childBodyArray as $value) {
                    $bodyPartsArray[] = $value;
                }
            }

            foreach ($bodyPartsArray as $data) {
                $insertData[] = [
                    'project_id' => 0,
                    'delete_id' => $data['id'],
                    'delete_name' => $data['bc_parts_name'],
                    'delete_table' => BcBodyParts::tableName(),
                    'operator_id' => $member->id,
                    'operator_name' => $member->realname,
                    'created_at' => time(),
                    'updated_at' => time()
                ];
            }

            // 删除部位表
            $ids = array_column($bodyPartsArray,'id');
            // 删除部位
            $data = BcBodyParts::deleteAll(['id' => $ids]);

            $transaction->commit();

            if (!$data) {
                return ['code' => 422, 'message' => '删除失败'];
            } else {
                return ['code' => 200, 'message' => '删除成功'];
            }

        } catch (\Exception $e) {
            $transaction->rollBack();
            return CommonHelper::api(422, $e->getMessage());
        }
    }

}
